<template>
  <a-modal v-model="visible" title="优惠券" :centered="true" width="1100px" :footer="false" destroyOnClose>
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="48" @keyup.enter.native="searchList">
          <a-col :md="8" :sm="24">
            <a-form-item label="搜索名称">
              <a-input v-model="queryParam.name" placeholder="" allowClear />
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-item label="搜索券ID">
              <a-input v-model="queryParam.ruleIds" placeholder="多个券ID，请使用英文,分隔" allowClear />
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-item label="类型">
              <a-select v-model="queryParam.type" placeholder="请选择" default-value="null" :getPopupContainer="triggerNode => triggerNode.parentNode">
                <a-select-option value="">不限</a-select-option>
                <a-select-option :value="0">现金券</a-select-option>
                <a-select-option :value="1">折扣券</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <!-- <a-col :md="8" :sm="24">
            <a-form-item label="创建日期">
              <a-range-picker style="width: 100%" format="YYYY-MM-DD HH:mm:ss" :placeholder="['开始时间', '结束时间']" v-model="queryParam.timePicker" />
            </a-form-item>
          </a-col> -->
          <a-col :md="24" :sm="24">
            <span class="table-page-search-submitButtons" :style="{ float: 'right', overflow: 'hidden' }">
              <a-button type="primary" @click="searchList">查询</a-button>
              <a-button style="margin-left: 8px" @click="resetList">重置</a-button>
              <a-button style="margin-left: 8px" type="primary" icon="plus" @click="handleAdd" :disabled="!(selectedRowKeys.length > 0)">批量添加</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <s-table
      ref="table"
      size="default"
      :rowKey="record => JSON.stringify(record)"
      :columns="columns"
      :data="loadData"
      :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
      :pagination="paginationProps"
    >
      <span slot="description" slot-scope="text">
        <ellipsis :length="13" tooltip>{{ text }}</ellipsis>
      </span>
      <span slot="type" slot-scope="text">{{ text | type }}</span>
      <span slot="action" slot-scope="text, record">
        <template>
          <a @click="add(record)">添加</a>
        </template>
      </span>
    </s-table>
  </a-modal>
</template>
<script>
import { STable, Ellipsis } from '@/views/box/components'
import { couponList } from '@/api/box/setting'
const columns = [
  { title: 'ID', dataIndex: 'id', align: 'center' },
  { title: '外部名称', dataIndex: 'name', align: 'center' },
  { title: '描述', dataIndex: 'description', align: 'center', scopedSlots: { customRender: 'description' } },
  { title: '类型', dataIndex: 'type', align: 'center', scopedSlots: { customRender: 'type' } },
  { title: '优惠额度', dataIndex: 'amount', align: 'center', customRender: (text, record) => (record.type == 1 ? record.discount * 100 + '%' : text) },
  { title: '有效期类型', dataIndex: 'expireType', align: 'center', customRender: text => (text == 1 ? '按领取时间顺延' : '指定时间') },
  { title: '有效期', align: 'center', customRender: (text, record) => (record.expireType == 1 ? record.endDays + '天' : record.expireType == 0 ? `${record.startDate}-${record.endDate}` : '') },
  { title: '操作', fixed: 'right', align: 'center', scopedSlots: { customRender: 'action' } }
]
export default {
  components: {
    STable,
    Ellipsis
  },
  data() {
    return {
      columns,
      visible: false,
      // 查询条件参数
      queryParam: {
        name: '',
        type: ''
      },
      // queryData: {},
      paginationProps: {
        total: 0,
        showTotal: total => `共有 ${total} 条数据`
      },
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => this.fetchData(parameter),
      selectedRowKeys: [],
      selectedRows: [],
      arg: ''
    }
  },
  filters: {
    type(type) {
      if (type === 0) {
        return '现金券'
      } else if (type === 1) {
        return '折扣券'
      }
    }
  },
  computed: {
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange
      }
    }
  },
  methods: {
    show(arg) {
      this.visible = true
      if (arg) this.arg = arg
    },
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    filterFields(values) {
      const formValue = {}
      Object.keys(values).forEach(i => {
        if (values[i] !== '' && values[i] !== undefined && values[i] !== null) {
          if (i == 'ruleIds') {
            formValue.ruleIds = values[i].split(',')
            formValue.ruleIds = formValue.ruleIds.map(e => e.trim())
          } else {
            formValue[i] = values[i]
          }

          /* if (i === 'timePicker') {
            if (values[i].length) {
              formValue.startTime = values[i][0].format('YYYY-MM-DD HH:mm:ss')
              formValue.endTime = values[i][1].format('YYYY-MM-DD HH:mm:ss')
            }
          } else {
            formValue[i] = values[i]
          } */
        }
      })
      return formValue
    },
    fetchData(parameter) {
      let params = {
        page: parameter,
        requestData: this.filterFields(this.queryParam)
      }
      return couponList(params).then(res => {
        if (res.code == 0) {
          return {
            data: res.data,
            page: res.page
          }
        } else {
          this.$message.warning(res.msg)
          return {
            data: [],
            page: {
              pageNo: 0,
              count: 0,
              pageSize: 10
            }
          }
        }
      })
    },
    searchList() {
      this.$refs.table.refresh(true)
    },
    resetList() {
      this.queryParam = {
        name: '',
        type: ''
      }
      this.onClearSelected()
      this.$refs.table.refresh(true)
    },
    onClearSelected() {
      this.selectedRowKeys = []
      this.selectedRows = []
    },
    handleAdd() {
      let list = this.selectedRowKeys.map(item => {
        let newItem = JSON.parse(item)
        return newItem
      })
      this.$emit('handleAddCoupons', list, this.arg)
      this.$message.success('已添加')
      this.onClearSelected()
    },
    add(record) {
      let list = [record]
      this.$emit('handleAddCoupons', list, this.arg)
      this.$message.success('已添加')
      this.onClearSelected()
    },
    // 清空列表选中
    onClearSelected() {
      this.selectedRowKeys = []
      this.selectionRows = []
    }
  }
}
</script>

